package com.example.message.lock;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.StandardOpenOption;

@DependsOn("sysMessageService")
@Service
public class SysFileLockServiceImpl implements SysFileLockService, InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${sitc.file.dir}")
    private String filePath;

    @Value("${server.port}")
    private int port;

    private Thread thread = null;

    public static final String LOCk = File.separator + "lock";

    @Override
    public void afterPropertiesSet() throws Exception {
        this.thread = new Thread(new Runnable() {
            @Override
            public void run() {
                FileLock fileLock = null;
                try {
                    File file = new File(filePath + LOCk);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    FileChannel fileChannel = FileChannel.open(file.toPath(), StandardOpenOption.READ, StandardOpenOption.WRITE);
                    fileLock = fileChannel.lock();
                    //开始启动服务，
                    //启动服务
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (fileLock != null) {
                        try {
                            fileLock.release();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        this.thread.setName("master thread");
        this.thread.setDaemon(true);
        this.thread.start();
    }

    @Override
    public void destroy() throws Exception {
        if (this.thread.isAlive()) {
            this.thread.interrupt();
        }
    }
}
